package com.liu.controller;

import com.alibaba.excel.EasyExcel;
import com.liu.dto.ServeTrainItemDto;
import com.liu.service.intf.ServeTrainService;
import com.liu.vo.PageBeanJson;
import com.liu.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/serveTrain/")
public class ServeTrainController {
    @Autowired
    private ServeTrainService serveTrainService;

    @GetMapping("list.do")
    public PageBeanJson<ServeTrainItemDto> list(int page, @RequestParam("limit") int pageSize) {
        return serveTrainService.list(page, pageSize);
    }

    @GetMapping("search.do")
    public PageBeanJson<ServeTrainItemDto> search(ServeTrainItemDto serveTrainItemDto, int page, @RequestParam("limit") int pageSize) {
        System.out.println("ServeTrainItemDto:字段" + serveTrainItemDto);
        return serveTrainService.search(page, pageSize, serveTrainItemDto);
    }

    @GetMapping("echarts.do")
    public R echarts() {
        return serveTrainService.trainSelect();
    }

    @PostMapping("insert.do")
    public R delete(ServeTrainItemDto serveTrainItemDto) {
        return serveTrainService.insert(serveTrainItemDto);
    }

    @PostMapping("del.do")
    public R delete(@RequestParam("id") int id, @RequestParam("trainItemId") int t_id) {
        return serveTrainService.delete(id, t_id);
    }

    //批量删除 JSON格式的数据请求
    @PostMapping("delBatch.do")
    public R deleteBatch(@RequestBody int[] ids) {
        return serveTrainService.deleteBatch(ids);
    }

    @PostMapping("update.do")
    public R update(ServeTrainItemDto serveTrainItemDto) {
        return serveTrainService.update(serveTrainItemDto);
    }

    //数据导入，Excel上传-解析-批量新增
    @PostMapping("upload.do")
    public R upload(MultipartFile file) throws IOException {
        return serveTrainService.savaBatch(file);
    }

    //数据导出
    @GetMapping("downall.do")
    public void down(HttpServletResponse response) throws IOException {
        //1.查询数据
        List<ServeTrainItemDto> list = serveTrainService.selectAll();
        //2.设置响应消息头
        response.setHeader("Content-disposition", "attachment;filename=" + System.currentTimeMillis() + ".xlsx");
        //3.写出内容
        EasyExcel.write(response.getOutputStream(), ServeTrainItemDto.class).
                sheet("自动导出").doWrite(list);
    }
}
